const { splitTrainingText } = require('../splite.js');
Page({
  data: {
    // 页面数据可以从后端获取，这里为示例数据
    planname: "健身挑战",
    remainingdays: 0,
    completeddays: '',
    todaydate: "",
    plan: {},
    step:{},
    totalCount: 0,
    completedCount: 0,
    progressPercent: 0,
    number:1,
    pid:0,
    doneCount:0,
    weeklyRecords: [] // 存储本周训练记录
  },

  onLoad() {
    const app = getApp();
    this.setTodayDate();
    const userInfo = wx.getStorageSync('userInfo')
    const totalCount = wx.getStorageSync('total')
    this.setData({
      doneCount : app.globalData.doneCount,
      totalCount : totalCount
    })
    wx.request({
      url: getApp().globalData.baseUrl + '/api/plan/id/'+userInfo.data.id,
      method: 'GET',
      data: {},
      header: {
        'Content-Type': 'application/json',
      },
      success: (res) => {
        console.log(res.data)
        this.setData({
          plan:res.data.data,
          pid:res.data.data.id
        });
        this.getStep(this.data.pid)
        this.calculateRemainingDays();
        this.computeProgress();
      },
      fail: (err) => {
        console.error('初始化数据获取失败:', err);
        wx.showToast({
          title: '数据加载失败',
          icon: 'none'
        });
      },
      complete: () => {
        // 无论成功失败，都关闭加载提示
        wx.hideLoading();
        this.setData({
          loading: false
        });
      }
    });
    this.initWeeklyRecords();
  },
  onShow() {
    // 页面每次显示时更新训练记录
    this.updateWeeklyRecords();
  },
  initWeeklyRecords() {
    const weekDays = ['日', '一', '二', '三', '四', '五', '六'];
    const records = [];
    const today = new Date();
    const currentDay = today.getDay(); // 获取今天是周几（0-6，0是周日）

    // 生成本周七天的基础数据
    for (let i = 0; i < 7; i++) {
      // 计算日期（获取本周的每一天）
      const date = new Date();
      date.setDate(today.getDate() - currentDay + i);
      
      // 默认状态（未开始）
      let status = '';
      let statusText = '未开始';
      
      // 关键修改：固定周六（索引6）和周日（索引0）为休息
      if (i === 0 || i === 6) {
        status = 'rest';
        statusText = '休息';
      } 
      // 其他日期正常处理
      else {
        // 标记今天为进行中（排除周末）
        if (i === currentDay) {
          status = 'active';
          statusText = '进行中';
        }
        
        // 从本地存储加载历史记录（排除周末）
        const dayKey = `train_${date.getFullYear()}_${date.getMonth() + 1}_${date.getDate()}`;
        const savedStatus = wx.getStorageSync(dayKey);
        
        if (savedStatus) {
          status = savedStatus;
          statusText = savedStatus === 'completed' ? '已完成' : '进行中';
        }
      }

      records.push({
        dayName: weekDays[i],
        status: status,
        statusText: statusText,
        date: date
      });
    }

    this.setData({
      weeklyRecords: records
    });
  },
  // 更新本周训练记录（跳过周末）
  updateWeeklyRecords() {
    const { weeklyRecords } = this.data;
    const today = new Date();
    const currentDay = today.getDay();
    
    // 只处理非周末的日期更新
    if (currentDay === 0 || currentDay === 6) {
      return; // 周末不更新状态
    }
    
    // 查找今天的记录并更新状态
    const updatedRecords = weeklyRecords.map((item, index) => {
      // 只更新今天的状态（非周末）
      if (index === currentDay) {
        const isCompleted = this.data.completedCount > 0 && 
                          this.data.completedCount === this.data.totalCount;
        
        return {
          ...item,
          status: isCompleted ? 'completed' : 'active',
          statusText: isCompleted ? '已完成' : '进行中'
        };
      }
      return item;
    });

    this.setData({
      weeklyRecords: updatedRecords
    });

    // 保存今天的状态到本地存储（非周末）
    const todayRecord = updatedRecords[currentDay];
    const dayKey = `train_${todayRecord.date.getFullYear()}_${todayRecord.date.getMonth() + 1}_${todayRecord.date.getDate()}`;
    wx.setStorageSync(dayKey, todayRecord.status);
  },
  calculateRemainingDays() {
    const totalDays = this.data.plan.duration;
    console.log("总数：",totalDays)
    const startDate = new Date(this.data.plan.createtime);
    console.log("创建：",startDate)
    const today = new Date(this.data.todaydate);
    console.log("今天：",today)
    const timeDiff = today - startDate;
    const daysPassed = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
    const remainingDays = Math.max(totalDays - daysPassed, 0);
    this.setData({
      remainingdays: remainingDays
    });
  },  
  getStep(pid){
    const requestData = {
    pid: this.data.pid, 
    number:this.data.number
  };
  console.log("pid:",this.data.pid)
  // 先判断 pid 是否有效，避免无效请求
  if (!pid || pid === 0) {
    wx.showToast({ title: '暂无关联的训练计划', icon: 'none' });
    return;
  }
  wx.request({
    url: getApp().globalData.baseUrl+'/api/step/getStepByPidAndNumber', 
    // 后端初始化接口
    method: 'POST',
    data: requestData,
    header: {
      'Content-Type': 'application/json',
    },
    success: (res) => {
      console.log("结果是：",res.data)
      this.setData({
        step:res.data.data,
        text:res.data.data.info
      })
      console.log("step里是",this.data.step)
      this.splitText();
    },
    fail: (err) => {
      console.error('初始化数据获取失败:', err);
      wx.showToast({
        title: '数据加载失败',
        icon: 'none'
      });
    },
    complete: () => {
      // 无论成功失败，都关闭加载提示
      wx.hideLoading();
      this.setData({
        loading: false
      });
    }
  });
  },
  splitText() {
    const text = splitTrainingText(this.data.text)
    const total = text.items.length
    this.setData({
      splitResult: text,
      // 初始化状态数组，所有项目默认为"未开始"
      trainingStatus: new Array(text.items.length).fill(0),
      totalCount: total,
      completedCount: 0,
    });
  },
  // 设置今日日期
  setTodayDate() {
    const date = new Date();
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    this.setData({
      todaydate: `${year}-${month}-${day}`
    });
    if (this.data.plan && this.data.plan.duration) {
      this.calculateRemainingDays();
    }
  },

  // 模拟获取训练计划数据
  fetchTrainingPlan() {
    // 实际项目中这里会调用wx.request获取后端数据
    wx.showLoading({
      title: '加载训练计划...'
    });

    // 模拟网络请求延迟
    setTimeout(() => {
      wx.hideLoading();
      // 这里可以根据接口返回的数据更新页面
      console.log('训练计划数据加载完成');
    }, 1000);
  },

  // 继续训练
  continueTraining(e) {
    // 获取当前训练项ID
    const itemId = e.currentTarget.dataset.id || 2; // 默认是进行中的项目
    wx.navigateTo({
      url: `/pages/training-detail/detail?id=${itemId}`,
      success: () => {
        console.log('跳转到训练详情页');
      },
      fail: (err) => {
        console.error('跳转失败:', err);
        wx.showToast({
          title: '跳转失败',
          icon: 'none'
        });
      }
    });
  },

  // 开始新训练
  startTraining(e) {
    const itemId = e.currentTarget.dataset.id;
    wx.showModal({
      title: '开始训练',
      content: '准备好开始这项训练了吗？',
      confirmText: '开始',
      cancelText: '稍后',
      success: (res) => {
        if (res.confirm) {
          wx.navigateTo({
            url: `/pages/training-detail/detail?id=${itemId}`
          });
        }
      }
    });
  },

  // 查看所有训练记录
  viewAllRecords() {
    wx.navigateTo({
      url: '/pages/training-records/records'
    });
  },

  // 导航栏切换
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab;
    switch(tab) {
      case 'home':
        wx.switchTab({
          url: '/pages/main/main'
        });
        break;
      case 'training':
        // 当前已经在训练页面，不需要跳转
        break;
      case 'mine':
        wx.switchTab({
          url: '/pages/mine/mine'
        });
        break;
    }
  },
  computeProgress() {
    const { plan, remainingdays } = this.data;
    const percent = ((plan.duration - remainingdays) / plan.duration) * 100;
    console.log("百分比为：",percent)
    const fixedPercent = Number(percent.toFixed(2));
    console.log("百分比为：",fixedPercent)
    this.setData({
      progressPercent: fixedPercent
    });
    console.log("数据类型:", typeof this.data.progressPercent, "值:", this.data.progressPercent);
    console.log("在新页面的count",this.data.doneCount)
  }
});
    